package jnpf.engine.custom.cmd.commons;

import jnpf.engine.util.SpringContextHolder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.common.engine.impl.el.VariableContainerWrapper;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;

import java.io.Serializable;
import java.util.Map;


@Data
@Slf4j
public class ExpressionCmd implements Command<Boolean>, Serializable {
    protected String processInstanceId;
    protected String exp;
    protected Map<String, Object> variableMap;
    protected RuntimeService runtimeService= SpringContextHolder.getBean(RuntimeService.class);
    protected ProcessEngineConfigurationImpl processEngineConfiguration = SpringContextHolder.getBean(ProcessEngineConfigurationImpl.class);

    public ExpressionCmd(String processInstanceId, String exp, Map<String, Object> variableMap) {
        this.processInstanceId = processInstanceId;
        this.exp = exp;
        this.variableMap = variableMap;
    }

    @Override
    public Boolean execute(CommandContext commandContext) {
        try{
            if(this.exp==null){
                return false;
            }

            Expression expression = processEngineConfiguration.getExpressionManager().createExpression(this.exp);
            Object value;
            if(StringUtils.isNotBlank(this.processInstanceId)){
                ExecutionEntity executionEntity = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(this.processInstanceId).includeProcessVariables().singleResult();
                value = expression.getValue(executionEntity);
            }else {
                VariableContainerWrapper variableContainerWrapper = new VariableContainerWrapper(variableMap);
                value = expression.getValue(variableContainerWrapper);
            }
            return value != null && "true".equals(value.toString());
        }catch (Exception e){
            log.error("动态条件解析出错:{}",e.getMessage());
            return Boolean.FALSE;
        }
    }
}

